package com.fzb.forum4j.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fzb.forum4j.dao.api.IUserDao;
import com.fzb.forum4j.po.Comment;
import com.fzb.forum4j.po.CommonArea;
import com.fzb.forum4j.po.QueryMode;
import com.fzb.forum4j.po.RequestRecord;
import com.fzb.forum4j.po.User;
import com.opensymphony.xwork2.ActionContext;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ParseTools {

	private static String home;
	
	public ParseTools() {
	};

	public static String isRecommend(int isRecommend) {
		return isRecommend == 1 ? "是" : "否";
	}

	public static String encrypt(String strSrc, String encName) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	public static String htmlspecialchars(String str) {
		// str = str.replaceAll("&", "&amp;");
		// str = str.replaceAll("<", "&lt;");
		// str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("<(.*)|(.*)(\n*)</>", "");
		str = str.replaceAll("<script(.*)|(.*)(\n*)</script>", "");
		return str;
	}

	public static String getDigestByContent(String str, int lenght) {
		// str = str.replaceAll("&", "&amp;");
		// str = str.replaceAll("<", "&lt;");
		// str = str.replaceAll(">", "&gt;");
		if (str.length() > lenght) {
			str = str.substring(0, lenght) + " ...";
		}
		return str;
	}
	
	
	public static String decodeBase64(String s) {
		if (s != null) {
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] b;
			try {
				b = decoder.decodeBuffer(s);
				return new String(b);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		return null;
	}

	public static String encodeBase64(String s) {
		if (s == null)
			return null;
		return (new BASE64Encoder()).encode(s.getBytes());
	}

	public static String encodeBase64(Long s) {
		if (s == null)
			return null;
		return (new BASE64Encoder()).encode(s.toString().getBytes());
	}

	public static void main(String[] args) {
		
		//System.out.println("Use SHA:"+encrypt("xxx","SHA-1"));
		
	}

	public static String getEnFromZh(String str) {
		try {

			String url = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=AnAydMWs7VRmfjQfsfbXXGjt&q="
					+ URLEncoder.encode(str, "UTF-8") + "&from=auto&to=auto";
			JSONObject json = new JSONObject(getJsonText(url));
			JSONArray ja = json.getJSONArray("trans_result");
			JSONObject j = (JSONObject) ja.get(0);
			return j.get("dst").toString();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getJsonText(String sSourceUrl) throws IOException {
		int HttpResult;
		URL url = new URL(sSourceUrl);
		String jsonstr = "";
		URLConnection urlconn = url.openConnection();
		urlconn.connect();
		HttpURLConnection httpconn = (HttpURLConnection) urlconn;
		HttpResult = httpconn.getResponseCode();

		if (HttpResult != HttpURLConnection.HTTP_OK) {

		} else {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlconn.getInputStream(), "UTF-8"));
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				jsonstr += inputLine;
			}
		}
		return jsonstr;
	}

	public static String simpleDateStr(Date data){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(data);
	}
	
	public static String simpleDateMsg(Date date) {
		System.out.println(date.getTime());
		long cdn = (Calendar.getInstance().getTimeInMillis() - date.getTime()) / 1000;
		if (cdn < 60) {
			return "刚刚";
		} else if (cdn <= 60 * 60 && cdn > 60) {
			return cdn / 60 + "分钟前";
		} else if (cdn > 3600 && cdn <= 86400) {
			return cdn / 3600 + "小时前";
		} else if (cdn > 86400 && cdn <= 2592000) {
			if (cdn / 86400 < 2) {
				return "昨天";
			}
			return cdn / 86400 + "天前";
		} else if (cdn > 2592000 && cdn <= 31104000) {
			return cdn / 2592000 + "月前";
		} else if (cdn > 31104000) {
			return cdn / 31104000 + "年前";
		}
		return "error";
	}
	
	static Pattern referer_pattern = Pattern.compile("@([^@^\\s^:]{1,})([\\s\\:\\,\\;]{0,1})");//@.+?[\\s:]

	/**
	 * 处理提到某人 @xxxx
	 * @param msg  传入的文本内容
	 * @param referers 传出被引用到的会员名单
	 * @return 返回带有链接的文本内容
	 */
	public static String _GenerateRefererLinks(String msg,User userF, List<Integer> referers,IUserDao userDao) {
		StringBuilder html = new StringBuilder();
		int lastIdx = 0;
	
		Matcher matchr = referer_pattern.matcher(msg);
		while (matchr.find()) {
			String origion_str = matchr.group();
			//System.out.println("-->"+origion_str);
			String str = origion_str.substring(1, origion_str.length()).trim();
			//char ch = str.charAt(str.length()-1);
			//if(ch == ':' || ch == ',' || ch == ';')
			//	str = str.substring(0, str.length()-1);
			//System.out.println(str);
			html.append(msg.substring(lastIdx, matchr.start()));
			
			User user = userDao.getUserNameByNickName(str);

			if(user!= null){
				if(!user.getUserName().equals(userF.getUserName())){
					html.append("<a href='"+home+"/u/"+user.getUserName()+"' class='referer' target='_blank'>@");
					html.append(str.trim());
					html.append("</a> ");
					if(referers != null && !referers.contains(user.getUserId())){
						referers.add(user.getUserId());
					}
				}
				else{
					html.append(origion_str);
				}
			}
			else{
				html.append(origion_str);
			}
			lastIdx = matchr.end();
			//if(ch == ':' || ch == ',' || ch == ';')
			//	html.append(ch);
		}
		html.append(msg.substring(lastIdx));
		return html.toString();
	}

	public static String getHome() {
		return home;
	}

	public static void setHome(String home) {
		ParseTools.home = home;
	}
	
	public static String getDate(){
		SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
		return sdf.format(new Date());
	}
	
	public static Integer getCountByMonth(){
		SimpleDateFormat sdf=new SimpleDateFormat("MM");
		Integer count=0;
		String month=sdf.format(new Date());
		Map<String, Set<Object>> map=((Map<String, Set<Object>>)ActionContext.getContext().getApplication().get("accessRecords"));
		for (Entry<String, Set<Object>>  m: map.entrySet()) {
			if(m.getKey().substring(0, 2).equals(month)){
				System.out.println(m.getValue().size());
				count+=m.getValue().size();
			}
		}
		return count;
	}
	public static Integer getCountAll(){
		Integer count=0;
		Map<String, Set<Object>> map=((Map<String, Set<Object>>)ActionContext.getContext().getApplication().get("accessRecords"));
		for (Entry<String, Set<Object>>  m: map.entrySet()) {
			count+=m.getValue().size();
		}
		return count;
	}
 
}
